// s3-runner.js
const esm = require("esm")(module);
const path = require("path");
const fs = require("fs");
const _ = require("lodash");

// 导入模块
const { readAllValues } = esm("../../../awakened-potential/helpers/readAllValues.js");
const checkAccuracy = esm("../../utils/checkAccuracy.js");
const select32NumbersByS3 = require("./select32NumbersByS3.js");

// 初始化参数
const allValues = readAllValues("m");
const allNumbers = Array.from({ length: 49 }, (_, i) => (i + 1).toString().padStart(2, "0"));
const windowSize = 5;
const useWindow = true;
const predictResults = [];

// 初始化转移矩阵
const transitionMatrix = {};
allNumbers.forEach((from) => {
  transitionMatrix[from] = {};
  allNumbers.forEach((to) => {
    transitionMatrix[from][to] = 0;
  });
});

// 主流程
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (temp.length === 0 || index === 0) return;

  // 预测
  const prediction = select32NumbersByS3(temp, transitionMatrix);
  predictResults.push(checkAccuracy(prediction, item.number));

  // 更新转移矩阵（不能偷看答案）
  const prev = allValues[index - 1].number;
  const curr = item.number;
  if (transitionMatrix[prev] && transitionMatrix[prev][curr] != null) {
    transitionMatrix[prev][curr]++;
  }
});

// 统计结果
const total = predictResults.length;
const correct = predictResults.filter((x) => x === 1).length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

let maxWrongStreak = 0;
let currentStreak = 0;
predictResults.forEach((res) => {
  if (res === 0) {
    currentStreak++;
    if (currentStreak > maxWrongStreak) {
      maxWrongStreak = currentStreak;
    }
  } else {
    currentStreak = 0;
  }
});

// 输出
console.log(`🎯 使用 S3 策略（马尔科夫预测）`);
console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);